package com.acoffee.web;

import com.acoffee.pojo.Message;
import com.acoffee.pojo.User;
import com.acoffee.service.Impl.UserServiceImpl;
import com.acoffee.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author acoffee
 * @create 2021-10-30 11:53
 */
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    public void checkUsername(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        boolean b = userService.queryByUsername(username);
        Message message = null;
        if(b){//用户名可用
            message = new Message(true,"<font color='green'>用户名可用</font>");
        }else {
            message = new Message(false,"<font color='red'>用户名已存在！</font>");
        }

        response(resp,message);
    }


    public void checkCode(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        String code = req.getParameter("code");
        String checkCode = (String)session.getAttribute("checkCode");
        System.out.println(code);
        System.out.println(checkCode);
        Message message = null;
        if (checkCode.equalsIgnoreCase(code)){
            message = new Message(true,"<font color='green'>验证码正确！</font>");
        }else {
            message = new Message(false,"<font color='red'>验证码错误！</font>");
        }
        response(resp,message);
    }

    public void register(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            req.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Map<String, String[]> map = req.getParameterMap();
        User user = new User();

        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        userService.register(user);

        resp.sendRedirect(req.getContextPath()+"/pages/register_ok.jsp");
    }

    public void active(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String code = req.getParameter("code");
        boolean flag = userService.active(code);

        if (flag){//激活成功
            resp.sendRedirect(req.getContextPath() + "/pages/active_ok.jsp");
        }else{//激活失败
            resp.sendRedirect(req.getContextPath() + "/pages/active_error.jsp");

        }
    }

    public void login(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = userService.login(username, password);

        if(user == null){
            //用户名或者密码错误
            req.setAttribute("msg","用户名或者密码错误");
            req.getRequestDispatcher("/pages/login.jsp").forward(req,resp);
        }else{
            if (user.getStatus().equals("0")){
                //未激活
                req.setAttribute("msg","未激活，请先激活");
                req.getRequestDispatcher("/pages/login.jsp").forward(req,resp);
            }else{
                req.getSession().setAttribute("user",user);
                resp.sendRedirect(req.getContextPath() + "/pages/index.jsp");
            }
        }
    }

    public void quit(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        req.getSession().removeAttribute("user");
        resp.sendRedirect(req.getContextPath()+"/pages/index.jsp");
    }

    public void modPwd(HttpServletRequest req,HttpServletResponse resp){
        String newpwd = req.getParameter("newpwd");
        String uid = req.getParameter("uid");

        boolean flag = userService.modPwd(Integer.parseInt(uid), newpwd);

        if (flag){
            response(resp,"修改密码成功，点击“确定”进入登录页面！");
            req.getSession().removeAttribute("user");
        }else{
            response(resp,"修改失败,请联系管理员！");
        }
    }

    public void addImg(HttpServletRequest req,HttpServletResponse resp) throws Exception {

	       /* Part part = req.getPart("file");

	        String name = part.getSubmittedFileName();*/

        UUID uuid = UUID.randomUUID();

        String str = uuid.toString().replace("-", "").substring(0, 5);

        req.setCharacterEncoding("utf-8");

        //获取父级目录
        String path = req.getServletContext().getRealPath("/icon/");

        File file = new File(path);

        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> fileItems = upload.parseRequest(req);

        String name = null;

        for (FileItem fileItem : fileItems) {
            //判断是否为普通的文件项
            if(!(fileItem.isFormField())){
                //上传文件
                name = str + "_" + fileItem.getName();

                File filePath = new File(file, name);

                System.out.println(name);

                fileItem.write(filePath);
            }else{

            }
        }
        String img_path = "icon/"+name;

        User user = (User) req.getSession().getAttribute("user");

        int uid = user.getId();

        new UserServiceImpl().saveImgPath(img_path,uid);

        req.getSession().setAttribute("pic",img_path);

        req.setAttribute("message","修改成功！");

        req.getRequestDispatcher("/pages/head_mod.jsp").forward(req,resp);
//	        resp.sendRedirect("/book/pages/touimg.jsp");
    }
}
